/*
 * Author:       zhuyehong
 * Date: 2012.2
 * Des:目录树模块.
 */
function HTREE(myname, position) {
  var tree = {};
  tree.myname = "";
  tree.position = "";
  tree.tree_html = "";
  tree.root = "";
  tree.rootID = '1';
  tree.selected = "";

  /* 版本定制功能begin */
  tree.first_level = "";

  tree.enhance_on_off = function (node) {
    if (node.children.length > 0) {
      return;
    }

    if (tree.first_level != '') {
      /* 恢复上一次选中的叶子节点的父亲节点样式 */
      var id = tree.first_level + " > table td[name='node']";
      var target = $(id);
    }

    if (node.nodeId.split('.').length == 2) {
      return;
    }

    var ids = node.nodeId.split('.');
    var first_level_id = ids[0] + '_' + ids[1];
    tree.first_level = '#' + tree.myname + '_' + first_level_id;

    var id = '#' + tree.myname + '_' + first_level_id + " > table td[name='node']";
    var target = $(id);
  };

  tree.enhance_show = function () {
    if (tree.selected.split('.').length == 2) {
      return;
    }

    var flag = '#' + tree.myname + '_' + tree.selected.replace(/\./, '_');

    if (flag.indexOf(tree.first_level) != 0 || tree.first_level == flag) {
      return;
    }

    if (tree.first_level != '') {
      var id = tree.first_level + " > table td[name='node']";
      var target = $(id);
    }
  };

  tree.enhance_clean = function () {
    tree.first_level = "";
  };

  /* 版本定制功能end */

  tree.node_struct = function () {
    return {
      nodeId: 'xxx',
      type: 'xxx',
      status: 'xxx',
      link: 'xxx',
      action: 'xxx',
      children: [],
      image: '',
      additional: '',
      values: '',
      parent: ''
    }
  };

  tree.getCurrentNode = function () {
    var c_node = tree.node_struct(), f_node;
    if (tree.selected.toString().length > 0) {
      f_node = tree.FIND_NODE(tree.selected, tree.root);

      if (f_node !== -1) {
        c_node.nodeId = f_node.nodeId;
        c_node.type = f_node.type;
        c_node.status = f_node.status;
        c_node.link = f_node.link;
        c_node.action = f_node.action;

        c_node.children = [];
        c_node.image = f_node.image;
        c_node.additional = f_node.additional;
        c_node.values = f_node.values;
        c_node.parent = '';
      }
    }

    return c_node;
  };

  tree.CLEAN_SELECTED = function () {
    tree.selected = "";
    tree.enhance_clean();
    tree.SHOW();
  };

  tree.OPEN_FST_LEVEL = function () {
    var stack = [];
    stack.push(tree.root);
    var i = 0, curNode = stack.pop();
    for (i = 0; i < curNode.children.length; i++) {
      curNode.children[i].status = 1;
    }
  };

  tree.FIND_NODE = function (nodeId, node) {
    nodeId = nodeId.toString();
    var find_pos = nodeId.split(".");
    var entry_pos = node.nodeId.split(".");

    if (find_pos.length <= entry_pos.length) {
      if (nodeId == node.nodeId) {
        return node;
      } else {
        return -1;
      }
    } else {
      var i = 0, tmp = [];
      for (i = 0; i < entry_pos.length; i++) {
        tmp.push(entry_pos[i]);
      }
      var tostr = tmp.toString().replace(/,/g, '.');

      if (tostr == node.nodeId) {
        tmp.push(find_pos[i]);
        tostr = tmp.toString().replace(/,/g, '.');

        var j = 0;
        for (j = 0; j < node.children.length; j++) {
          if (node.children[j].nodeId == tostr) {
            return tree.FIND_NODE(nodeId, node.children[j]);
          }
        }
        return -1;
      } else {
        return -1;
      }
    }
  };

  tree.FIND_NODE_BY_NAME = function (additional, node) {
    if (additional == node.additional) {
      return node;
    } else {
      var j = 0;
      for (j = 0; j < node.children.length; j++) {
        if (additional == node.children[j].additional) {
          return node.children[j];
        }

        if (node.children[j].children.length > 0) {
          var nd = tree.FIND_NODE_BY_NAME(additional, node.children[j]);
          if (nd != -1) {
            return nd;
          }
        }
      }
    }

    return -1;
  };

  tree.ADD = function (parentId, nodeId, type, link, action, image, additional, values) {
    var myId = parentId + '.' + nodeId;
    var o = tree.node_struct();
    o.nodeId = myId;
    var parent = tree.FIND_NODE(parentId, tree.root);

    if (parent == -1) {
      return;
    }

    var me = tree.FIND_NODE(myId, parent);
    if (me == -1) {
      parent.type = '1';
      o.type = type;
      o.status = 0;
      o.link = link;
      o.action = action;
      o.image = image;
      o.additional = additional;
      o.values = values;
      o.parent = parent;

      values = values.toString();
      if (values.indexOf('@') != -1) {
        o.values_stack = values.split('@');
      }

      parent.children.push(o);
      return o;
    }
  };

  tree.getMaxId = function (node) {

    var maxId = 0, i = 0, nodeId = 0;

    for (i = 0; i < node.children.length; i++) {
      nodeId = 0;
      try {
        nodeId = node.children[i].nodeId.split('.').pop();
        maxId = maxId > nodeId ? maxId : nodeId;
      } catch (e) {
        Modal.open("Error", e.message, "error");
      }
    }

    return maxId;
  };

  tree.ADD_BanUnique = function (parentId, nodeId, type, link, action, image, additional, values) {
    var isExist = tree.FIND_NODE_BY_NAME(additional, tree.root);

    if (isExist != -1) {
      return;
    }

    var myId = parentId + '.' + nodeId;
    var o = tree.node_struct();
    o.nodeId = myId;
    var parent = tree.FIND_NODE(parentId, tree.root);

    if (parent == -1 || parent.type == 0) {
      return;
    }
    var i = 0;
    for (i = 0; i < parent.children.length; i++) {
      if (parent.children[i].additional == additional) {
        return;
      }
    }

    var me = tree.FIND_NODE(myId, parent);
    if (me == -1) {
      parent.type = '1';
      o.type = type;
      o.status = 0;
      o.link = link;
      o.action = action;
      o.image = image;
      o.additional = additional;
      o.values = values;
      o.parent = parent;

      values = values.toString();
      if (values.indexOf('@') != -1) {
        o.values_stack = values.split('@');
      }

      parent.children.push(o);
      return o;
    }
  };

  tree.getAdditionalName = function (i) {
    return "o.additional" + i;
  };

  tree.DEL = function (nodeId) {
    var find_pos = nodeId.split(".");
    var parentId = nodeId.substring(0, nodeId.lastIndexOf("."));
    var parent = tree.FIND_NODE(parentId, tree.root), i = 0;

    for (i = 0; i < parent.children.length; i++) {
      if (parent.children[i].nodeId == tree.selected) {
        tree.selected = '';
      }

      if (parent.children[i].nodeId == nodeId) {
        parent.children.splice(i, 1);
      }

      if (parent.children.length == 0) {
        parent.type = '0';
      }
    }
  };

  tree.EMPTY_NODE = function (nodeId) {
    var node = tree.FIND_NODE(nodeId, tree.root);
    if (node != -1) {
      node.children = [];
    }
  };

  tree.MOUNT = function (childnode) {
    tree.FIND_NODE(parentId, tree.root);
  };

  tree.PRINT = function (nodeId) {
    var node = tree.FIND_NODE(nodeId, tree.root);

    if (node != -1) {
      var str = "nodeId:" + node.nodeId + "\n";
      str += "type:" + node.type + "\n";
      str += "status:" + node.status + "\n";
      str += "link:" + node.link + "\n";
      str += "action:" + node.action + "\n";
      str += "children:" + node.children.length + "\n";
      str += "image:" + node.image + "\n";
      str += "additional:" + node.additional + "\n";
      Modal.open("Print", str, "ok");
    } else {
      Modal.open("Print", "Node" + nodeId + "not Exist", "ok");
    }
  };

  tree.ON_OFF = function (nodeId) {

    var node = tree.FIND_NODE(nodeId, tree.root);

    if (typeof node.action == 'function') {
      node.action(node);
    }

    if (node.type == 1) {
      /* 展开文件夹 */
      node.status = node.status ? 0 : 1;
      tree.CREATE_TREE();
      $(tree.position).empty();

      document.getElementById(tree.position.substring(1, tree.position.length)).innerHTML = tree.tree_html;
    } else {
      /* 改变选中叶子节点状态 */
      var id = '#' + tree.myname + '_' + tree.selected.replace(/\./g, '_') + " > table td[name='node']";

      if (tree.selected != '') {
        /* 恢复上一次选中的叶子节点样式 */
        var s = $(id);
        $(s[0]).children("a").removeClass();
        $(s[0]).children("a").addClass("treeIconNode treeIcon");
        $(s[1]).children("a").removeClass();
        $(s[1]).children("a").addClass("treeLeaf");
      }

      /* selected:上传选择节点，nodeId：本次点击节点 */
      tree.selected = node.nodeId;

      id = '#' + tree.myname + '_' + node.nodeId.replace(/\./g, '_') + " > table td[name='node']";
      var s = $(id);
      /* 改变当前选中的叶子节点的样式 */
      $(s[0]).children("a").removeClass();
      $(s[0]).children("a").addClass("treeIconFocus treeIcon");
      $(s[1]).children("a").removeClass();
      $(s[1]).children("a").addClass("selectedTreeLeaf");
    }

    if (node != -1) {
      tree.enhance_on_off(node);
    }
    tree.enhance_show();

    if (USER.hasModule(Branch.Modules.XML_TREE)) {
      /* 设置导航提示,各产品线参数整理后使用 */
      var treeNode = node;
      var path = treeNode.additional;

      while (treeNode.parent != '') {
        treeNode = treeNode.parent;
        if (treeNode.additional != '') {
          path = treeNode.additional + ' >> ' + path;
        }
      }

      Path.setNavPath(path, 0);
    }
  };

  tree.OVER = function (nodeId) {
    if (tree.selected != nodeId) {
      var node = tree.FIND_NODE(nodeId, tree.root);
      if (node.type == 1) {
        return;
      }

      var id = '#' + tree.myname + '_' + nodeId.replace(/\./g, '_') + " > table td[name='node']";
      var s = $(id);
      /* 改变鼠标悬浮时的节点样式 */
      $(s[0]).children("a").removeClass();
      $(s[0]).children("a").addClass("treeIconHover treeIcon");
    }
  };

  tree.OUT = function (nodeId) {
    if (tree.selected != nodeId) {
      var node = tree.FIND_NODE(nodeId, tree.root);
      if (node.type == 1) {
        return;
      }

      var id = '#' + tree.myname + '_' + nodeId.replace(/\./g, '_') + " > table td[name='node']";
      var s = $(id);

      /* 改变鼠标离开时的节点样式 */
      $(s[0]).children("a").removeClass();
      $(s[0]).children("a").addClass("treeIconNode treeIcon");
    }
    tree.enhance_show();
  };

  tree.CONTEXTMENU = function (event, nodeId) {
    var F_NODE = tree.FIND_NODE(nodeId, tree.root);
    if (F_NODE.ContextMenu != null) {
      if (typeof F_NODE.ContextMenu == 'function') {
        F_NODE.ContextMenu(event, F_NODE);
      } else {
        throw new Error("ContextMenu is not a function!");
      }
    } else {
      return;
    }
  };

  tree.CREATE_NODE = function (node) {
    var node_html = "<div class='clip' style='display:block;'>", cArr = [];
    cArr.push(node_html);

    var i = 0, divId, j = 0;
    for (i = 0; i < node.children.length; i++) {
      if (node.children[i].children.length > 0 || node.children[i].type == 1) {
        if (node.children[i].status == 0) {
          divId = tree.myname + "_" + node.children[i].nodeId.replace(/\./g, '_');
          cArr.push("<div id='" + divId + "'>");
          cArr.push("<table cellspacing='0' cellpadding='0' ><tr>");

          j = 0;
          for (j = 0; j < node.children[i].nodeId.split('.').length - 2; j++) {
            /* 占位空图片背景颜色 */
            cArr.push("<td class='treeIconEmpty'>");
            cArr.push("&nbsp;</td>");
          }

          /* 关闭的文件夹的背景颜色*/
          cArr.push("<td name='node' class='treeTd' onmouseout='");
          cArr.push(tree.myname);
          cArr.push(".OUT(\"");
          cArr.push(node.children[i].nodeId);
          cArr.push("\")' onmouseover='");
          cArr.push(tree.myname);
          cArr.push(".OVER(\"");
          cArr.push(node.children[i].nodeId);
          cArr.push("\")'>");

          cArr.push("<a href='#'class='treeIconFolder treeIcon'onclick='")
          cArr.push(tree.myname);
          cArr.push(".ON_OFF(\"");
          cArr.push(node.children[i].nodeId);
          cArr.push("\")'>&nbsp;</a>");
          cArr.push("</td>");

          /* 关闭的文件夹的文字背景眼色 */
          cArr.push("<td name='node' class='treeTd' id='" + divId + "_click" + "' nowrap='nowrap'>");

          cArr.push("<a href='#' class='treeLeaf' onfocus='this.blur();' onclick='");

          cArr.push(tree.myname);
          cArr.push(".ON_OFF(\"");
          cArr.push(node.children[i].nodeId);
          cArr.push("\")'>");
          cArr.push((node.children[i].additional ? node.children[i].additional : ('node ' + node.children[i].nodeId)));
          cArr.push("</a></td>");
          cArr.push("</tr></table>");
          cArr.push("</div>");
        } else {
          divId = tree.myname + "_" + node.children[i].nodeId.replace(/\./g, '_');
          cArr.push("<div id='" + divId + "'");
          cArr.push(">");
          cArr.push("<table  cellspacing='0' cellpadding='0' ><tr>");

          j = 0;

          for (j = 0; j < node.children[i].nodeId.split('.').length - 2; j++) {
            /* 占位空图片背景颜色 */
            cArr.push("<td class='treeIconEmpty'>");
            cArr.push("&nbsp;</td>");
          }

          /* 打开的文件夹的背景颜色 */
          cArr.push("<td name='node' class='treeTd' onmouseout='");
          cArr.push(tree.myname);
          cArr.push(".OUT(\"");
          cArr.push(node.children[i].nodeId);
          cArr.push("\")' onmouseover='");
          cArr.push(tree.myname);
          cArr.push(".OVER(\"");
          cArr.push(node.children[i].nodeId);
          cArr.push("\")'>");

          cArr.push("<a href='#'class='treeIconFolderOpen treeIcon'onclick='")
          cArr.push(tree.myname);
          cArr.push(".ON_OFF(\"");
          cArr.push(node.children[i].nodeId);
          cArr.push("\")'>&nbsp;</a>");
          cArr.push("</td>");

          /* 打开的文件夹的文字背景颜色 */
          cArr.push("<td name='node' class='treeTd' id='" + divId + "_click" + "' nowrap='nowrap'>");

          cArr.push("<a href='#' class='treeLeaf' onfocus='this.blur();' onclick='");

          cArr.push(tree.myname);
          cArr.push(".ON_OFF(\"");
          cArr.push(node.children[i].nodeId);
          cArr.push("\")'>");
          cArr.push((node.children[i].additional ? node.children[i].additional : ('node ' + node.children[i].nodeId)));
          cArr.push("</a></td>");
          cArr.push("</tr></table>");
          cArr.push("</div>");
          cArr.push(tree.CREATE_NODE(node.children[i]));
        }
      } else {
        divId = tree.myname + "_" + node.children[i].nodeId.replace(/\./g, '_');
        cArr.push("<div id='" + divId + "'");
        cArr.push(">");
        cArr.push("<table  cellspacing='0' cellpadding='0' ><tr>");

        j = 0;
        for (j = 0; j < node.children[i].nodeId.split('.').length - 2; j++) {
          /* 占位空图片背景颜色 */
          cArr.push("<td class='treeIconEmpty'>");
          cArr.push("&nbsp;</td>");
        }

        if (node.children[i].nodeId == tree.selected) {
          /* 当前选中的叶子节点的图片背景颜色 */
          cArr.push("<td name='node' class='treeTd' onmouseout='");
          cArr.push(tree.myname);
          cArr.push(".OUT(\"");
          cArr.push(node.children[i].nodeId);
          cArr.push("\")' onmouseover='");
          cArr.push(tree.myname);
          cArr.push(".OVER(\"");
          cArr.push(node.children[i].nodeId);
          cArr.push("\")'>");

          cArr.push("<a href='#'class='treeIconFocus treeIcon'onclick='")
          cArr.push(tree.myname);
          cArr.push(".ON_OFF(\"");
          cArr.push(node.children[i].nodeId);
          cArr.push("\")'>&nbsp;</a>");
          cArr.push("</td>");

          /* 当前选中的叶子节点的文字背景颜色 */
          cArr.push("<td name='node' class='treeTd' id='" + divId + "_click" + "' nowrap='nowrap'>");

          cArr.push("<a href='#' class='treeLeaf' onfocus='this.blur();' onclick='");

          cArr.push(tree.myname);
          cArr.push(".ON_OFF(\"");
          cArr.push(node.children[i].nodeId);
          cArr.push("\")'>");
          cArr.push((node.children[i].additional ? node.children[i].additional : ('node ' + node.children[i].nodeId)));
          cArr.push("</a></td>");
        } else {
          /* 当前非选中的叶子节点的图片背景颜色 */
          cArr.push("<td name='node' class='treeTd' onmouseout='");
          cArr.push(tree.myname);
          cArr.push(".OUT(\"");
          cArr.push(node.children[i].nodeId);
          cArr.push("\")' onmouseover='");
          cArr.push(tree.myname);
          cArr.push(".OVER(\"");
          cArr.push(node.children[i].nodeId);
          cArr.push("\")'>");

          cArr.push("<a href='#'class='treeIconNode treeIcon'onclick='")
          cArr.push(tree.myname);
          cArr.push(".ON_OFF(\"");
          cArr.push(node.children[i].nodeId);
          cArr.push("\")'>&nbsp;</a>");
          cArr.push("</td>");

          /* 当前非选中的叶子节点的文字背景颜色 */
          cArr.push("<td name='node' class='treeTd' id='" + divId + "_click" + "' nowrap='nowrap'> ");

          cArr.push("<a href='#' class='treeLeaf' onfocus='this.blur();' onclick='");

          cArr.push(tree.myname);
          cArr.push(".ON_OFF(\"");
          cArr.push(node.children[i].nodeId);
          cArr.push("\")'>");
          cArr.push((node.children[i].additional ? node.children[i].additional : ('node ' + node.children[i].nodeId)));
          cArr.push("</td>");
        }

        cArr.push("</tr></table>");
        cArr.push("</div>");
      }
    }

    cArr.push("</div>");

    return cArr.join("");
  };

  tree.CREATE_TREE = function () {
    tree.tree_html = "<div class='htree' id = '" + tree.myname + "'>";

    if (tree.root.children.length > 0) {
      tree.tree_html = tree.tree_html + "<div>";
      tree.tree_html = tree.tree_html + tree.CREATE_NODE(tree.root);
      tree.tree_html = tree.tree_html + "</div>";
    }

    tree.tree_html = tree.tree_html + "</div>";

    return tree.tree_html;
  };

  tree.SHOW = function () {
    tree.CREATE_TREE();
    $(tree.position).empty();
    $(tree.position).append(tree.tree_html);
    tree.enhance_show();
  };

  tree.SEARCH_ALL = function (nodeId, type, addition) {
    var stack = [];
    var node = tree.FIND_NODE(nodeId, tree.root);
    stack.push(node);

    var i = 0, j = 0;

    while (stack.length > 0) {
      var curNode = stack.pop();
      curNode.status = 0;

      if (curNode.values_stack != null && curNode.values_stack.length > 0) {
        switch (type) {
          case '1':
            if (curNode.values_stack[3].indexOf('*') == -1) {
              if (curNode.values_stack[3].toLocaleLowerCase() == addition.toLocaleLowerCase()) {
                return curNode;
              }
            } else {
              var struct_names = curNode.values_stack[3].split('*');

              for (j = 0; j < struct_names.length; j++) {
                if (struct_names[j].toLocaleLowerCase() == addition.toLocaleLowerCase()) {
                  return curNode;
                }
              }
            }
            break;
          case '2':
            if (curNode.values_stack[0].indexOf('*') == -1) {
              if (curNode.values_stack[0].toLocaleLowerCase() == addition.toLocaleLowerCase()) {
                return curNode;
              }
            } else {
              var struct_ids = curNode.values_stack[0].split('*');

              for (j = 0; j < struct_ids.length; j++) {
                if (struct_ids[j].toLocaleLowerCase() == addition.toLocaleLowerCase()) {
                  return curNode;
                }
              }
            }
            break;
          case '3':
            if (curNode.values_stack[2].indexOf('*') == -1) {
              if (curNode.values_stack[2].toLocaleLowerCase() == addition.toLocaleLowerCase()) {
                return curNode;
              }
            } else {
              var struct_cnnames = curNode.values_stack[2].split('*');

              for (j = 0; j < struct_cnnames.length; j++) {
                if (struct_cnnames[j].toLocaleLowerCase() == addition.toLocaleLowerCase()) {
                  return curNode;
                }
              }
            }
            break;
          default:
            break;
        }
      }

      for (i = 0; i < curNode.children.length; i++) {
        stack.push(curNode.children[i]);
      }
    }
    return null;
  };

  tree.CLOSE_ALL = function () {
    var stack = [];
    stack.push(tree.root);
    var i = 0;

    while (stack.length > 0) {
      var curNode = stack.pop();
      curNode.status = 0;

      for (i = 0; i < curNode.children.length; i++) {
        stack.push(curNode.children[i]);
      }
    }
  };

  tree.OPEN_ALL = function () {
    var stack = [];
    stack.push(tree.root);
    var i = 0;

    while (stack.length > 0) {
      var curNode = stack.pop();
      curNode.status = 1;

      for (i = 0; i < curNode.children.length; i++) {
        stack.push(curNode.children[i]);
      }
    }
  };

  /* init */
  ( function () {
    tree.root = tree.node_struct();
    tree.root.nodeId = '1';
    tree.position = "#" + position;
    tree.myname = myname;
  }());

  return tree;
}

/**
 * 存储、获取当前子窗口URL
 */
var URLManager = ( function () {
  var o = {};

  function setURL(url) {
    o.url = url;
    o.action = "";
  }

  function getURL() {
    return o.url;
  }

  function setAction(action) {
    o.action = action;
  }

  function getAction() {
    return o.action;
  }

  return {
    setURL: setURL,
    getURL: getURL,
    setAction: setAction,
    getAction: getAction
  };
}());

/**
 * 目录树
 */
var Path = ( function () {

  function show(node, url) {
    var structID = node.values.split("@")[0], //
      structName = node.values.split("@")[1], //
      treeNode = node, path = treeNode.additional;
    lmt_struct.structName = structName;
    lmt_struct.structID = structID;
    top.G_MIX_MUL_INTANCES = "['" + structID + "']";

    document.getElementById("contentMainFrame").src = url + "?r=" + top.VALIDATION_STRING;

    /*设置导航提示*/
    while (treeNode.parent !== '') {
      treeNode = treeNode.parent;
      if (treeNode.additional !== '')
        path = treeNode.additional + ' >> ' + path;
    }

    URLManager.setURL(url);
  }

  function showLeaf(node) {
    show(node, "business/config/lmtParamView.asp");
  }

  function showMulLeaf(node) {
    show(node, "business/config/MultiInstance.html");
  }

  function gotoLog(node) {
    show(node, "business/config/LogViewer.asp");
  }

  var navigationPath = [], navigationObj = {
    path: [],
    position: ''
  };

  function initNavigationPath() {
    navigationObj.position = '#' + "navInfo";
  }

  function showNavigationPath() {
    var path = '', i = 0, len = 0;
    for (i = 0, len = navigationObj.path.length; i < len; i += 1) {
      if (i === 0) {
        path = navigationObj.path[0];
      } else {
        path += ' >> ' + navigationObj.path[i];
      }
    }

    $(navigationObj.position).text(path);
  }

  function cleanNavPath(begin) {
    if (begin > navigationObj.path.length) {
      return;
    }
    navigationObj.path = navigationObj.path.splice(0, begin + 1);
  }

  function setNavPath(name, pos) {
    cleanNavPath(pos);
    navigationObj.path[pos] = name;
    showNavigationPath();
  }

  initNavigationPath();
  return {
    showLeaf: showLeaf,
    showMulLeaf: showMulLeaf,
    gotoLog: gotoLog,
    setNavPath: setNavPath
  };

}());

/**
 * global vars
 */
var G_MIX_PARAM = {
  mixStructID: '',
  mixMembers: '',
  mixTitles: ''
}, G_MIX_MUL_INTANCES;

/**
 * Class ManTree
 */
( function () {
  //private vars
  var g_XMLRoot = null, g_treeObj = null, g_treeUrl = "", //
    StructNameIndex = -1, LanguageEn = false;

  /**
   * class ManTree
   * @param {String} treeUrl, file path of the tree config xml.
   */
  ManTree = function (treeUrl) {
    StructNameIndex = top.c_paramRowIndex.StructName;
    LanguageEn = (Language === "EN");
    g_treeUrl = treeUrl;
  };

  /**
   * Public interface, init tree
   *  @param {Object} instance of HTREE
   */
  ManTree.prototype.initTree = function (treeObj) {
    g_treeObj = treeObj;
    g_XMLRoot = get_xmlDoc();
    nodeInit();
  };

  ///////////// private functions ///////////////
  function nodeInit() {
    var trees = $(g_XMLRoot).find("earth > root"), //
      tree = [], i = 0, len = 0, level = 0, footerIndex = 0;

    for (i = 0, len = trees.length; i < len; i += 1) {
      level = window.parseInt($(trees[i]).attr("level"), 10);
      if (USER.isAuthorised(level)) {
        tree = trees[i];
        break;
      }
    }

    if ($(tree).size() === 0) {
      return;
    }

    footerIndex = baseInfoTreeObj.root.children.length;
    addNode(tree, baseInfoTreeObj.rootID, footerIndex);

    g_treeObj.SHOW();
  }

  function addNode(nd, parentId, myId) {
    var x_parentId = parentId, x_myId = myId, childrens = [], i = 0, len = 0, //
      nodeName = "", node = null, structID = "", structDesc = "", structName = "", //
      url = "", mix_member = "", mix_title = "", structIDs = "", mixStructID = "";

    if (nd.tagName === "root") {
      childrens = $(nd).children();
      i = 0;
      len = 0;
      for (i = 0, len = childrens.length; i < len; i += 1, x_myId += 1) {
        addNode(childrens[i], parentId, x_myId);
      }
    } else if (nd.tagName === "branch") {
      childrens = $(nd).children();
      if (LanguageEn) {
        nodeName = $(nd).attr("en_title");
      } else {
        nodeName = $(nd).attr("title");
      }
      node = g_treeObj.ADD_BanUnique(x_parentId, x_myId.toString(), '1', '', '', '', nodeName, '');

      for (i = 0, len = childrens.length; i < len; i += 1) {
        addNode(childrens[i], node.nodeId, i);
      }
    } else if (nd.tagName === "leaf") {
      nodeName = $(nd).text();
      structID = $(nd).attr("structID");
      mixStructID = $(nd).attr("mixStructID") || "";
      structDesc = -1;
      structName = "unknow";
      url = $(nd).attr("url");
      mix_member = $(nd).attr("member");
      mix_title = $(nd).attr("title");
      structIDs = $(nd).attr("structs");

      if (typeof (structID) !== "undefined" && structID !== null) {
        structDesc = localDB.T_search("c_param", "StructID", structID);
        if (structDesc.length === 0) {
          // 数据库没有改结构体
          return;
        }
        structName = structDesc[0][StructNameIndex];
      }
      if (structName === "unknow") {
        structName = nodeName;
      }
      if (LanguageEn) {
        nodeName = $(nd).attr("en_title");
      }

      g_treeObj.ADD_BanUnique(x_parentId, x_myId.toString(), '', '', gotoPage, '', nodeName, //
        structID + '@' + structName + '@' + url + '@' + mix_member + "@" + mix_title + //
        "@" + structIDs + "@" + mixStructID);
    }
  }

  function gotoPage(node) {
    G_MIX_MUL_INTANCES = "";
    var nodeValueArr = node.values.split("@"), //
      url = nodeValueArr[2], //
      ifNd = document.getElementById("contentMainFrame");

    lmt_struct.structID = nodeValueArr[0];
    lmt_struct.structName = nodeValueArr[1];
    G_MIX_PARAM.mixMembers = nodeValueArr[3];
    G_MIX_PARAM.mixTitles = nodeValueArr[4];
    G_MIX_MUL_INTANCES = nodeValueArr[5];
    G_MIX_PARAM.mixStructID = nodeValueArr[6] !== "" ? nodeValueArr[6] : null;

    ifNd.src = url + '?r=' + top.VALIDATION_STRING;
    URLManager.setURL(url);
  }

  /**
   *  加载xml ,return DOM object, or null on error.
   */
  function get_xmlDoc() {
    var root = null;

    $.ajax({
      type: "post",
      url: g_treeUrl,
      async: false,
      dataType: "xml",
      success: function (data, textStatues) {
        root = data;
      },
      error: function () {
        throw new Error("get xml error");
      }
    });
    return root;
  }

}());

